﻿var com= com|| {};
com.viewModel = com.viewModel || {};

com.viewModel.search = function (data) {
    var me = this;
    me.idField = data.idField;
    me.urls = data.urls;
    me.resx = data.resx;
    me.dataSource = data.dataSource;
    me.form = ko.mapping.fromJS(data.form);
    delete me.form.__ko_mapping__;

    me.grid = {
        url: me.urls.query,
        queryParams: ko.observable()
    };
    me.grid.queryParams(data.form);

    me.search = function () {
        var param = ko.toJS(me.form);
        me.grid.queryParams(param);
    };
    me.add = function () {
        com.openTab(me.resx.addTitle, me.urls.add);
    };
    me.close = function() {
        com.close();
    };

    //-- notice that grid.datagrid() will be declared in koext.js
    me.edit = function () {
        var row = me.grid.datagrid("getSelected");
        if (!row) return com.message("error", me.resx.noneSelection);
        com.openTab(me.resx.editTitle, me.urls.edit + row[me.idField]);
    };
    me.grid.onDblClickRow = me.edit;

    me.remove = function () {
        var row = me.grid.datagrid("getSelected");
        if (!row) return com.message("error", me.resx.noneSelection);

        com.message("comfirm", me.resx.removeComfirm, function (b) {
            if (b) {
                com.ajax({
                    type: "DELETE",
                    url: me.urls.remove + row[me.idField],
                    success: function (data) {
                        if (data) {
                            com.message("success", me.resx.removeSuccess);
                            me.search();
                        } else {
                            com.message("error", me.resx.removeFailed);
                        }
                    }
                });
            }
        });
    };
}